package com.zsh.weather.ln.https

import com.yechaoa.yutilskt.LogUtilKt
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit

class HttpManager private constructor() {
    lateinit var httpClient: OkHttpClient
    private val connectTimeOut = 10L
    private val readTimeOut = 10L
    private val writeTimeOut = 10L
    private val timeUnit = TimeUnit.SECONDS
    private var interceptors: ArrayList<Interceptor> = ArrayList()
    private var netWorkInterceptors: ArrayList<Interceptor> = ArrayList()

    companion object {
        fun instace() = Holder.INSTACE
    }

    private object Holder {
        val INSTACE = HttpManager()
        init {
            INSTACE.initHttpClient()
        }
    }

    private fun initHttpClient(): OkHttpClient {
        LogUtilKt.d("初始化。。。。。。。。。。。。。。。。。。。。。。。")
        var builder = OkHttpClient.Builder()
            .connectTimeout(connectTimeOut, timeUnit)
            .readTimeout(readTimeOut, timeUnit)
            .writeTimeout(writeTimeOut, timeUnit)
        builder = initInterceptors(builder, interceptors)
        builder = initNetWorkInterceptors(builder, netWorkInterceptors)
        httpClient = builder.build()
        return httpClient
    }

    fun addInterceptors(interceptors: ArrayList<Interceptor>) {
        this.interceptors = interceptors
    }

    fun addNetWorkInterceptors(networkInterfaces: ArrayList<Interceptor>) {
        this.netWorkInterceptors = netWorkInterceptors
    }

   private fun initInterceptors(
        builder: OkHttpClient.Builder,
        interceptors: ArrayList<Interceptor>?
    ): OkHttpClient.Builder {
        interceptors?.forEach {
            if (it != null) {
                builder?.addInterceptor(it)
            }
        }
        return builder
    }

    private fun initNetWorkInterceptors(
        builder: OkHttpClient.Builder,
        networkInterfaces: ArrayList<Interceptor>?
    ): OkHttpClient.Builder {
        networkInterfaces?.forEach {
            if (it != null) {
                builder?.addNetworkInterceptor(it)
            }
        }
        return builder
    }
}